package com.oneraku.service.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oneraku.service.domain.WishOrder;
import com.oneraku.service.dao.WishOrderMapper;
import com.oneraku.service.exceptions.InfoException;
import com.oneraku.service.service.IWishOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oneraku.service.utils.AuthBean;
import com.oneraku.service.utils.R;
import com.oneraku.service.utils.RequestUserUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 心愿单 服务实现类
 * </p>
 *
 * @author renhui <337375464@qq.com>
 * @since 2020-02-25
 */
@Service
public class WishOrderServiceImpl extends ServiceImpl<WishOrderMapper, WishOrder> implements IWishOrderService {
    private void checkBean(WishOrder wishOrder){
        if(StringUtils.isEmpty(wishOrder.getUrl()) && wishOrder.getUrl().indexOf("http") != 0){
            throw new InfoException("代拍链接不能为空");
        }
    }
    @Override
    public R listWishOrder(WishOrder wishOrder) {
        AuthBean authBean = RequestUserUtils.getUser();
        return R.okPage(page(wishOrder.page(), Wrappers.<WishOrder>lambdaQuery().eq(WishOrder::getUid,authBean.getId())));
    }

    @Override
    public R editWishOrder(WishOrder wishOrder) {
        String agentBuyId = wishOrder.getId();
        if(StringUtils.isEmpty(agentBuyId)){
            throw new InfoException("更新标识未知");
        }
        checkBean(wishOrder);
        AuthBean authBean = RequestUserUtils.getUser();
        wishOrder.setUid(authBean.getId());
        return R.ok(save(wishOrder));
    }

    @Override
    public R delWishOrder(WishOrder wishOrder) {
        String agentBuyIds = wishOrder.getId();
        if(StringUtils.isEmpty(agentBuyIds)){
            throw new InfoException("删除标识未知");
        }
        AuthBean authBean = RequestUserUtils.getUser();
        Set<String> ids = Arrays.stream(agentBuyIds.split(",")).collect(Collectors.toSet());
        List<WishOrder> wishOrderList =  list(Wrappers.<WishOrder>lambdaQuery().in(WishOrder::getId,ids).eq(WishOrder::getUid,authBean.getId()));
        List<String> validIds =  wishOrderList.stream().map(item->item.getId()).collect(Collectors.toList());
        if(validIds.size() >0 ){
             removeByIds(validIds);
        }
        return R.ok(validIds);
    }

    @Override
    public R addWishOrder(WishOrder wishOrder) {
        checkBean(wishOrder);
        wishOrder.setId(null);
        AuthBean authBean = RequestUserUtils.getUser();
        wishOrder.setUid(authBean.getId());
        return R.ok(save(wishOrder));
    }
}
